//
//  CustomTabBarController.m
//  tabbardemo
//
//  Created by 虞嘉伟 on 2025/2/24.
//


#import "CustomTabBarController.h"
#import "CustomTabBarItemView.h"
#import <YYKit.h>
#import <Masonry.h>


@interface CustomTabBarController ()
{
    UIView *_customTabBar;
}
@property (nonatomic, strong) NSArray<CustomTabBarItemView *> *customTabBarItems;

@end

@implementation CustomTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTabBar];
    [self setupCustomTabBarItems];
}

- (void)setupTabBar {
    // 隐藏默认的 TabBar
    self.tabBar.hidden = YES;
    
    // 创建自定义的 TabBar 背景
    UIView *customTabBar = [UIView new];
    _customTabBar = customTabBar;
    customTabBar.backgroundColor = UIColorHex(#1B1B1B); //[UIColor whiteColor];
    customTabBar.layer.shadowColor = [UIColor blackColor].CGColor;
    customTabBar.layer.shadowOffset = CGSizeMake(0, -2);
    customTabBar.layer.shadowOpacity = 0.1;
    customTabBar.layer.shadowRadius = 4;
    [self.view addSubview:customTabBar];
    [customTabBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(49+SAFE_AREA_INSETS.bottom);
    }];
}

- (void)setupCustomTabBarItems {
    // 创建自定义 TabBarItem 视图
    NSArray *titles = @[@"Home", @"Order", @"Mine"];
    NSArray *icons_normal = @[[UIImage imageNamed:@"home_normal"], [UIImage imageNamed:@"order_normal"], [UIImage imageNamed:@"mine_normal"]];
    NSArray *icons_select = @[[UIImage imageNamed:@"home_select"], [UIImage imageNamed:@"order_select"], [UIImage imageNamed:@"mine_select"]];
    
    NSMutableArray *tabBarItems = [NSMutableArray array];
    for (NSInteger i = 0; i < titles.count; i++) {
        CustomTabBarItemView *itemView = [[CustomTabBarItemView alloc] initWithTitle:titles[i] image:icons_normal[i] selectedImage:icons_select[i]];
        itemView.tag = i;
        itemView.userInteractionEnabled = YES;
        [itemView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabBarItemTapped:)]];
        [_customTabBar addSubview:itemView];
        [tabBarItems addObject:itemView];
    }
    [tabBarItems mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [tabBarItems mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(49);
    }];
    self.customTabBarItems = tabBarItems;
    
    // 默认选中第一个
    [self setSelectedIndex:0];
}

- (void)tabBarItemTapped:(UITapGestureRecognizer *)gesture {
    NSInteger index = gesture.view.tag;
    [self setSelectedIndex:index];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    [super setSelectedIndex:selectedIndex];
    
    // 更新自定义 TabBarItem 的选中状态
    for (NSInteger i = 0; i < self.customTabBarItems.count; i++) {
        self.customTabBarItems[i].isSelected = (i == selectedIndex);
    }
}

@end
